package com.zk.iotgateway.netty.handler;

import com.zk.iotgateway.manager.GlobalManager;
import com.zk.iotgateway.domain.locator.LocatorDO;
import com.zk.iotgateway.service.IotDispatchService;
import com.zk.iotgateway.util.StringUtils;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 *
 * 处理器
 * 相关业务逻辑处理
 * @author:mn.m
 * @create 2019-04-17 下午 02:28
 **/
@Component
@ChannelHandler.Sharable
public class SocketInHandler extends ChannelInboundHandlerAdapter{
    private static final Logger log = LoggerFactory.getLogger(SocketInHandler.class);

    @Autowired
    private IotDispatchService iotDispatchService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        InetSocketAddress insocket = (InetSocketAddress)channel.remoteAddress();
        String ipAddress = StringUtils.formatIpAddress(insocket.getHostName(), String.valueOf(insocket.getPort()));
        String clientIpAddress = ipAddress;// ctx.channel().remoteAddress().toString().replaceAll("\\/", "");// clientIpAddress = "127.0.0.1:53956"
        System.out.println("线上"+ipAddress);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        GlobalManager.DEVMANAGER.remove(channel);
        InetSocketAddress insocket = (InetSocketAddress)channel.remoteAddress();
        System.out.println("下线了"+insocket.getAddress()+insocket.getPort());

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String info = (String) msg;
            System.out.println("网关--"+ctx.channel().localAddress() + " 接收数据：" + info);
            LocatorDO locatorDO = new LocatorDO(info);
            //登录包01
            if ("01".equals(locatorDO.getMsgType())) {
                String devId = locatorDO.getContent();
                GlobalManager.DEVMANAGER.put(ctx.channel(),devId);
                iotDispatchService.send(ctx, devId + "*" + info);
                ctx.writeAndFlush("787801010D0A");
            }
            //定位包10
            else if ("10".equals(locatorDO.getMsgType())) {

                //iotDispatchService.send(ctx, GlobalManager.DEVMANAGER.get(ctx.channel()) + "*" + info);
                ctx.writeAndFlush("78780010"+StringUtils.getYMDHMS()+"0D0A");
            }else if ("13".equals(locatorDO.getMsgType())){
               // iotDispatchService.send(ctx, GlobalManager.DEVMANAGER.get(ctx.channel()) + "*" + info);
                ctx.writeAndFlush("787801130D0A");
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // TODO Auto-generated method stub
        super.exceptionCaught(ctx, cause);
        /**
         * 发生异常时删除缓存中对应的client的缓存
         */
        Channel channel = ctx.channel();
        GlobalManager.DEVMANAGER.remove(channel);
        InetSocketAddress insocket = (InetSocketAddress)channel.remoteAddress();
        String ipAddress = StringUtils.formatIpAddress(insocket.getHostName(), String.valueOf(insocket.getPort()));
        String clientIpAddress = ipAddress;
        System.out.println("异常ip"+ipAddress);
        cause.printStackTrace();
    }
    /**
     * 心跳检测触发的事件通过本方法捕获
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            System.out.println("心跳检测开始");
            IdleState state = ((IdleStateEvent) evt).state();
            if(state == state.READER_IDLE ){
                ChannelFuture fcutrue =  ctx.close();
                fcutrue.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        Channel channel = future.channel();
                        InetSocketAddress insocket = (InetSocketAddress)channel.remoteAddress();
                        String ipAddress = StringUtils.formatIpAddress(insocket.getHostName(), String.valueOf(insocket.getPort()));
                        String key = ipAddress;
                        System.out.println(key+"心跳超时下线成功....");
                    }
                });
            }
        }else{
            super.userEventTriggered(ctx, evt);
        }

    }

}
